package org.apache.ocean;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.ocean.ShardInfo.Index;
import org.apache.ocean.ShardInfo.Index.IndexFile;


// TODO: test ShardReplicator
// TODO: solve problem when try to obtain file it's not there
public class ShardReplicator {
	private URL url;
  private ShardInfo localShardInfo;
  private ShardInfo remoteShardInfo;
	
	public ShardReplicator(URL url, ShardInfo localShardInfo, ShardInfo remoteShardInfo, Interface shardInterface) {
		this.url = url;
		this.localShardInfo = localShardInfo;
		this.remoteShardInfo = remoteShardInfo;
		ChangedUtil<String,Index> indexChanges = new ChangedUtil<String,Index>(localShardInfo.indices, remoteShardInfo.indices);
		
		Map<String,ChangedUtil<String,IndexFile>> fileChanges = new HashMap<String,ChangedUtil<String,IndexFile>>();
		
		for (String indexID : indexChanges.newLocal.keySet()) {
			ShardInfo.Index localIndex = localShardInfo.indices.get(indexID);
			ShardInfo.Index remoteIndex = remoteShardInfo.indices.get(indexID);
			ChangedUtil<String,IndexFile> indexFileChanges = checkFiles(localIndex, remoteIndex);
			if (indexFileChanges != null) {
				fileChanges.put(indexID, indexFileChanges);
			}
		}
		ShardChangedEvent shardChangedEvent = new ShardChangedEvent();
		shardChangedEvent.indexChanges = indexChanges;
		shardChangedEvent.filesChanges = fileChanges;
		shardInterface.shardChanged(shardChangedEvent);
	}
	
	public static interface Interface {
		public void shardChanged(ShardChangedEvent event);
	}
	
	public static class ShardChangedEvent {
		public ChangedUtil<String,Index> indexChanges;
		public Map<String,ChangedUtil<String,IndexFile>> filesChanges;
	}
	
	public ChangedUtil<String,IndexFile> checkFiles(ShardInfo.Index localIndex, ShardInfo.Index remoteIndex) {
		ChangedUtil<String,IndexFile> changedUtil = new ChangedUtil<String,IndexFile>(localIndex.files, remoteIndex.files);
		if (changedUtil.hasChanges()) return changedUtil;
		return null;
	}
}
